import {queryRootCategory, queryChildrenCategory, queryProBaseByCategoryId, validSn, warrantyCardByPhone, queryAllWarrantyBySn} from '../../api/aftersale.js'
import {queryTree} from '../../api/sys'
import WxValidate from "../../utils/WxValidate";

Page({
    /**
     * 页面的初始数据
     */
    data: {
        parentCategory: [],
        childrenCategory: [],
        proBaseList: [],
        breakTypeList: [],
        ifOriginalReturnList: [
            {text: '否', value: '0'},
            {text: '是', value: '1'}
        ],
        warrantyCardList: [],
        snList: [],

        showChildrenCategory: false,
        showParentCategory: false,
        showBreakType: false,
        showProBase: false,
        showIfOriginalReturn: false,
        showWarrantyCard: false,
        showSnList: false,

        formData: {
            proId: "",
            proName: "",
            code: "",
            sn: "",
            breakType: "",
            breakInfo: "",
            ifOriginalReturn: "",
            ownerMobile: ""
        },

        orderItemList: []
    },

    /**
     * ---- 父级分类方法----
     */
    showParentCategory(event) {
        // event.detail 为当前输入的值
        queryRootCategory({}).then(res => {
            let {data, success} = res
            if (success && data.length > 0) {
                var arr = [];
                data.forEach(item => {
                    arr.push({text: item.name, value: item.id})
                })
                this.setData(
                    {
                        parentCategory: arr,
                        showParentCategory: true
                    }
                )
            }
            wx.hideLoading()
        })
    },

    ShowChildrenCategory(e) {
        queryChildrenCategory({"parentId": e.detail.value.value}).then(res => {
            let {data, success} = res
            if (success && data.length > 0) {
                var arr = [];
                data.forEach(item => {
                    arr.push({text: item.name, value: item.id})
                })
                this.setData(
                    {
                        childrenCategory: arr,
                        showParentCategory: false,
                        showChildrenCategory: true
                    }
                )
            } else {
                wx.showModal({
                    content: "该分类下没有产品，请选择其他分类进行查找",
                    showCancel: false,
                })
            }
            wx.hideLoading()
        })
    },

    onParentClose() {
        this.setData({
            showParentCategory: false
        })
    },


    /**
     * ---- 子级分类方法----
     */
    showProBase(e) {
        const {value} = e.detail;
        queryProBaseByCategoryId({"categoryId": value.value}).then(res => {
            let {data, success} = res
            if (success && data.length > 0) {
                data.forEach(item => {
                    item.value = item.id;
                    item.text = item.name;
                })
                this.setData(
                    {
                        proBaseList: data,
                        showChildrenCategory: false,
                        showProBase: true,
                    }
                )
            } else {
                wx.showModal({
                    content: "该分类下没有产品，请选择其他分类进行查找",
                    showCancel: false,
                })
            }
            wx.hideLoading()
        })
    },
    onChildrenClose() {
        this.setData({
            showChildrenCategory: false
        })
    },


    /**
     * ---- 子级下产品方法----
     */
    selectProBase(e) {
        const {value} = e.detail;
        this.setData({
            'formData.proId': value.id,
            'formData.proName': value.name,
            "formData.code": value.code,
            showProBase: false
        });
    },

    onProBaseClose() {
        this.setData({
            showProBase: false
        })
    },


    /**
     * --- 展示故障类型 --
     */
    openBreakType() {
        this.setData({
            showBreakType: true
        });
    },
    selectBreakType(e) {
        const {value} = e.detail;
        const carTypeValue = value.filter(item => !!item)
        this.setData({
            'formData.breakType': carTypeValue[carTypeValue.length - 1].value,
            'formData.breakTypeLabel': carTypeValue[carTypeValue.length - 1].text,
            showBreakType: false
        })
    },
    onBreakTypeClose() {
        this.setData({
            showBreakType: false
        })
    },

    /**
     *  ---- 展示是否原返 ---
     */
    openIfOriginalReturn() {
        this.setData({
            showIfOriginalReturn: true
        });
    },
    selectIfOriginalReturn(e) {
        const {value} = e.detail;
        this.setData({
            'formData.ifOriginalReturn': value.text,
            showIfOriginalReturn: false
        });
    },
    onIfOriginalReturnClose() {
        this.setData({
            showIfOriginalReturn: false
        })
    },

    setSn(event) {
      if (event.detail.length === 20) {
        const params = {
          "inSn:EQ:blurCondition": event.detail,
          "OR:outSn:EQ:blurCondition": event.detail
        }
        let _this = this
        queryAllWarrantyBySn(params).then(res => {
          let { data, success } = res
          if (success && data.cardCode) {
            _this.setData({
              'formData.cardCode': data.cardCode,
              'formData.ownerMobile': data.ownerMobile,
              'formData.code': data.proCode,
              'formData.proName': data.proName,
            })
          } else {
            wx.showModal({
              content: "未查询到SN信息",
              showCancel: false,
            })
          }       
        })
      }
    },

    setBreakInfo(event) {
        this.setData({
            'formData.breakInfo': event.detail
        })
    },
    phoneNumberChange(event) {
      this.setData({
        'formData.ownerMobile': event.detail
      })
      if(/^1[3|4|5|6|7|8|9][0-9]{9}$/.test(event.detail)){ 
        let _this = this
        warrantyCardByPhone({"ownerMobile:EQ": event.detail}).then(res => {
          let { data, success } = res
          if (success && data.length) {
            const warrantyCardList = data.map(item => {                  
              return {
                value: [item.inSn, item.outSn],
                text: item.cardCode
              }
            })
            _this.setData({
              warrantyCardList: warrantyCardList
            })
          } else {
            wx.showModal({
                content: "未查询到质保卡信息",
                showCancel: false,
            })
          }
        })
      } 
    },
    toggleShowWarrantyCardPop() {
      if (this.data.warrantyCardList && this.data.warrantyCardList.length) {
        this.setData({
          showWarrantyCard: !this.data.showWarrantyCard
        })
      } else {
        const flag = /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(this.data.formData.ownerMobile)
        const msg = !this.data.formData.ownerMobile ? '请先输入联系方式' : (flag && this.data.warrantyCardList.length ? '未查询到联系方式对应的质保卡' : '请输入正确的联系方式')
        wx.showModal({
          content: msg,
          showCancel: false
        })
      }
    },
    selectWarrantyCard(e) {
      const {value} = e.detail;
      this.setData({
          'formData.cardCode': value.text,
          snList: value.value,
          showWarrantyCard: false
      });
    },
    toggleSignPop() {
      this.setData({
        showSnList: !this.data.showSnList
      })
    },
    selectSignPop(e) {
      const {value} = e.detail;
      this.setData({
          'formData.sn': value,
          showSnList: false
      });
      this.setSn({detail: value})
    },
    tapSn() {
      if (this.data.snList && this.data.snList.length) {
        this.toggleSignPop()
      }
    },

    /**
     * 取消
     */
    cancelBtn() {
        wx.navigateBack()
    },
    submitBtn() {
        if (!this.WxValidate.checkForm(this.data.formData)) {
            wx.showModal({
                content: this.WxValidate.errorList[0].msg,
                showCancel: false,
            })
            return false;
        }
        if (this.data.formData.sn) {
            validSn(this.data.formData).then(res => {
                let {success} = res;
                var this_ = this;
                if (success) {
                    this.jump(this_.data.formData);
                }
            })
        } else {
            this.jump(this.data.formData);
        }
    },

    jump(formData) {
        this.data.orderItemList.push(formData);
        var this_ = this;
        wx.navigateTo({
            url: '/pages/logisticsAdd/logisticsAdd',
            success: function (res) {
                res.eventChannel.emit('acceptDataFromOpenerPage', {data: this_.data.orderItemList})
            }
        })
        wx.hideLoading()
    },


    initValidate() {
        const rules = {
            proName: {
                required: true
            },
            ownerMobile: {
              required: true,
              tel: true
            },
            breakType: {
                required: true
            },
            breakInfo: {
                required: true
            },
            ifOriginalReturn: {
                required: true
            }
        }
        const messages = {
            proName: {
                required: '请选择产品'
            },
            ownerMobile: {
              required: '填写联系电话',
              tel: '请输入正确的联系方式'
            },
            breakType: {
                required: '请选择故障类型'
            },
            breakInfo: {
                required: '填写故障描述'
            },
            ifOriginalReturn: {
                required: '请选择是否原返'
            }
        }
        this.WxValidate = new WxValidate(rules, messages)
    },
    toQueryTree() {
      queryTree({code:"breakdown_type"}).then(res => {
        let {data,success} = res
        if (success) {
          const columns1 = data.map(item => {
              return {
                  value: item.id,
                  text: item.name,
                  children: item.children
              }
          })
          const columns2 = columns1[0].children && columns1[0].children.length > 0 && columns1[0].children.map(item => {
              return {
                  value: item.id,
                  text: item.name,
                  children: item.children
              }
          })
          const columns3 = columns2 && columns2[0].children && columns2[0].children.length > 0 && columns2[0].children.map(item => {
              return {
                  value: item.id,
                  text: item.name,
                  children: item.children
              }
          })
          const breakTypeList = [
              {
                  values: columns1
              },
              {
                  values: columns2
              },
              {
                  values: columns3
              }
          ]

          this.setData({
            breakTypeList: breakTypeList
          })
        }
      })
    },
    onBreakTypeType(event) {
      const { picker, value, index } = event.detail;
      picker.setColumnValues(index + 1, value[index].children.map(item => {
          return {
              value: item.id,
              text: item.name,
              children: item.children
          }
      }))
      if (index === 0) {
          picker.setColumnValues(index + 2, value[index].children[0].children.map(item => {
              return {
                  value: item.id,
                  text: item.name,
                  children: item.children
              }
          }))
      }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.proId) {
            this.setData({
                'formData.proId': options.proId,
                'formData.proName': options.proName,
                'formData.code': options.code,
                'formData.sn': options.sn
            })
        }

        //验证规则函数
        this.initValidate()

        let _this = this

        const eventChannel = this.getOpenerEventChannel();

        if (Object.keys(eventChannel).length > 0) {
            eventChannel.on('inputSelectParts', function (data) {
                let arr = [];
                arr = data.data.orderItemList;
                _this.setData({
                    'orderItemList': arr
                })
            });
        }

        this.toQueryTree()
    }
    ,

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    }
    ,

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    }
    ,

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    }
    ,

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    }
    ,

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    }
    ,

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    }
    ,

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
    ,

})
